package com.cmw.udp.l301;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

/**
 * UDP 提供者，用于提供服务
 */
public class UDPProvider {

    public static void main(String[] args) {
        System.out.println("UDPProvider Started.");

        //DatagramSocket 监听 20000 端口
        try {
            DatagramSocket ds = new DatagramSocket(20000);

            //构建接收实体
            byte[] buf = new byte[512];
            DatagramPacket receivePack = new DatagramPacket(buf, buf.length);
            ds.receive(receivePack);
            String clientIP = receivePack.getAddress().getHostAddress();
            int port = receivePack.getPort();
            byte[] dataArr = receivePack.getData();
            int len = receivePack.getLength();
            String data = new String(dataArr);
            System.out.println(String.format("UDPProvider receive from ip : %s\t port:%d\t data:%s", clientIP, port, data));

            //构建回送数据
            String responseData = String.format("Receive data with len %d", len);
            DatagramPacket responsePack = new DatagramPacket(responseData.getBytes(), responseData.length(), receivePack.getAddress(), port);
            ds.send(responsePack);
            //
            System.out.println("UDPProvider Finished.");
            ds.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
